package vn.edu.saigontech.ncms.service.impl;

import java.util.Collections;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;

import vn.edu.saigontech.ncms.model.bookstore.ItemTitle;
import vn.edu.saigontech.ncms.model.comparator.ItemTitleComparator;
import vn.edu.saigontech.ncms.model.program.Level;
import vn.edu.saigontech.ncms.model.program.Program;
import vn.edu.saigontech.ncms.service.ItemService;
import vn.edu.saigontech.ncms.service.ItemTitleService;

@SuppressWarnings("unchecked")
public class ItemTitleServiceImpl extends HibernateGenericService<ItemTitle, Long> implements ItemTitleService {

	@Override
	public boolean deleteById(Long id) {
		if(!ItemService.INSTANCE.findByTitleId(id).isEmpty())
			return false;
		return super.deleteById(id);
	}
	
	@Override
	public List<ItemTitle> findByProgram(Program program) {
		Criteria criteria = this.createCriteria();
		criteria.add(Restrictions.eq("program", program));
		List<ItemTitle> titles = criteria.list();
		Collections.sort(titles, new ItemTitleComparator());
		return titles;
	}

	@Override
	public List<ItemTitle> findByLevel(Level level) {
		Criteria criteria = this.createCriteria();
		criteria.createAlias("levels", "level", Criteria.LEFT_JOIN);
		criteria.add(Restrictions.eq("level.id", level.getId()));
		List<ItemTitle> items = criteria.list();
		Collections.sort(items, new ItemTitleComparator());
		return items;
	}
}